Ext.define('appmod.controller.knowledge.usergroup.Startup', {
    extend: 'Ext.app.Controller',

    views: [
    	'knowledge.usergroup.Dashboard',
		'knowledge.usergroup.Form',
		'knowledge.usergroup.UserAssignForm'
    ],

	models : [
	],
	
    stores: [
		'knowledge.usergroup.Page',
		'AvailableUsers'
	],	

    refs: [
		{ref: 'usergroupDashboard', selector: 'knowledge-usergroup-dashboard'}
	],

    init: function() {

		var me = this;
    	this.control({

			'knowledge-usergroup-dashboard button[action=createUserGroup]': {
				click:{
					fn: me.showAddUserGroupForm,
					scope:me
				}
			},
			'knowledge-usergroup-dashboard button[action=updateUserGroup]': {
				click:{
					fn:me.showUpdateUserGroupForm,
					scope:me
				}
			},
			'knowledge-usergroup-dashboard button[action=deleteUserGroup]': {
				click:{
					fn:me.showDeleteUserGroupDialog,
					scope:me
				}
			},
			'knowledge-usergroup-dashboard button[action=assignUserMember]': {
				click:{
					fn:me.showAssignUserMemberDialog,
					scope:me
				}
			}
			
						

    	});


    },
	
		
	loadInitComp : function() {
		var mainPanel = Ext.create('appmod.view.knowledge.usergroup.Dashboard' , {
			region : 'center',
			border:false,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	
	onLaunch:function(app) {
		
		var me = this;
		
		var dsUserGroupPage  = me.getKnowledgeUsergroupPageStore();
		var usergroupDashboard = me.getUsergroupDashboard();
		if (dsUserGroupPage) {
			usergroupDashboard.bindStore( dsUserGroupPage );
		}


	},
	
	// create dinfoe
	showAddUserGroupForm : function() {
		var me = this;
		var win = null;
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '用户组',
				closable : true,
				//closeAction:'hide',
				modal:true,
				width : 320,
				height : 200,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.usergroup.form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addUserGroup'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-usergroup-form");

		var saveBtn = win.down('button[action="addUserGroup"]');
		saveBtn.on("click",me.saveUserGroup , me , {
			window : win
		});


		if ( !win.isVisible() ) {
			win.show();
		}
		
	},
	
	
	saveUserGroup:function(btn , event , eOpts) {
		var me = this;

		var listView = me.getUsergroupDashboard();

		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('knowledge-usergroup-form');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/knowledge/usergroup/submit_adding.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});
	},
	
	// create user info
	showUpdateUserGroupForm : function() {

		var me = this;
		var defListView = me.getUsergroupDashboard();
			
		var selModel = defListView.getSelectionModel();
		var recs = selModel.getSelection();

		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个用户组',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (recs.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '只能选择一个用户组',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}


		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '用户组',
				closable : true,
				//closeAction:'hide',
				modal:true,
				width : 320,
				height : 200,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.usergroup.form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'editUserGroup'
        				}
				    ]
				}]	
			});
		}
		
		var formPanel = win.down("knowledge-usergroup-form");
		
		formPanel.load({
			params:{
				id:recs[0].getId()
			},
			url: '../../data/resource/knowledge/usergroup/load.json',
            waitMsg: '数据加载中'	
		});
		

		var saveBtn = win.down('button[action="editUserGroup"]');
		saveBtn.on("click",me.updateUserGroup , me , {
			window : win
		});
	
		if ( !win.isVisible() ) {
			win.show();			
		}
				
	},
	

	updateUserGroup:function(btn , event , eOpts) {
		var me = this;

		var listView = me.getUsergroupDashboard();

		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('knowledge-usergroup-form');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/knowledge/usergroup/submit_updating.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});
	},
	
	showDeleteUserGroupDialog:function() {
		var me = this;
		
		var defListView = me.getUsergroupDashboard();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();


		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择用户组',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < rec.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			removeRecs += rec[i].get('groupName');
		}
		
		Ext.MessageBox.confirm('确认', '肯定要删除用户组: "'+removeRecs+'"?',me.confirmDeletedUserGroup , me);
	},
	
	confirmDeletedUserGroup:function(confirm , other) {

		var me = this;
		
		var defListView = me.getUsergroupDashboard();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();
		
		if (confirm == "no") {
			return;
		}

		var jsonObj = [];
		for (var i = 0 ; i < rec.length ; i++) {
			jsonObj.push(rec[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/knowledge/usergroup/submit_deleteall.json',
				method:'post',
				jsonData:jsonObj,
				success: function(response, opts) {
					// --- update load ---
					defListView.getStore().load();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}	
		
	},
	
	showAssignUserMemberDialog :function() {
		var me = this;
		var defListView = me.getUsergroupDashboard();
			
		var selModel = defListView.getSelectionModel();
		var recs = selModel.getSelection();

		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个用户组',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (recs.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个用户组',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}

		var dsKnowAvaiUsers = me.getAvailableUsersStore();
		dsKnowAvaiUsers.reload();

		var fieldStores = {
			'dsUser' : dsKnowAvaiUsers
		};
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '指定用户成员',
				closable : true,
				modal:true,
				//closeAction:'hide',
				width : 500,
				height : 320,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,					
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge-usergroup-userassignform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'saveUserAssign'
        				}
				    ]
				}]	
			});
		}
		
		var formPanel = win.down("knowledge-usergroup-userassignform");

		var saveBtn = win.down('button[action="saveUserAssign"]');
		saveBtn.on("click",me.saveUserAssign , me , {
			window : win
		});


		// --- init form data ---
		var form = formPanel.getForm();
		
		if (recs.length > 0) {
			var rec = recs[0];
			
			var hiddenFieldId = formPanel.down('hiddenfield[name=id]');
			hiddenFieldId.setValue( rec.getId() );
			
			var groupName = formPanel.down('displayfield[name=groupName]');
			groupName.setValue( rec.get('groupName') );
			
		}

		form.load({
			params:{
				id:recs[0].getId()
			},
			url: '../../data/resource/knowledge/usergroup/load_userassign.json',
            waitMsg: '数据加载中'	
		});

		
		if ( !win.isVisible() ) {
			win.show();			
		}
		
	},
	
	saveUserAssign :function(btn , event , eOpts) {
		var me = this;
		var defListView = me.getUsergroupDashboard();
		var dsUser = defListView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('knowledge-usergroup-userassignform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/knowledge/usergroup/user/submit_assign.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});		
	}

	
	
});